//
//  AppDelegate.swift
//  HyphenateIMDemo
//
//  Created by Shang Hai Rui Xi on 2018/12/28.
//  Copyright © 2018 Shang Hai Rui Xi. All rights reserved.
//

import UIKit
import Hyphenate
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        let apnsCertName = "HyphenateIMDemo"
        let hyphenateAppKey = "1156170408115964#hyphenateimdemo"
        
        UNUserNotificationCenter.current().delegate = self

        
//        EaseSDKHelper.share()?.hyphenateApplication(application, didFinishLaunchingWithOptions: launchOptions, appkey: hyphenateAppKey, apnsCertName: apnsCertName, otherConfig: [:])
        
        let options = EMOptions.init(appkey: hyphenateAppKey)
        options?.apnsCertName = apnsCertName
        EMClient.shared()?.initializeSDK(with: options)
        
        window = UIWindow.init(frame: UIScreen.main.bounds)

        let vc = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewVC") as! ViewController
        vc.tabBarItem.title = "设置"
        vc.title = "设置"
        let nav1 = UINavigationController.init(rootViewController: vc)
        
        let vc2 = NearListViewController()
        vc2.tabBarItem.title = "列表"
        vc2.title = "列表"
        let nav2 = UINavigationController.init(rootViewController: vc2)
        
        let vc3 = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MineVC") as! MineViewController
        vc3.tabBarItem.title = "我的"
        vc3.title = "我的"
        let nav3 = UINavigationController.init(rootViewController: vc3)
        
        
        let rootVc = UITabBarController()
        rootVc.addChild(nav1)
        rootVc.addChild(nav2)
        rootVc.addChild(nav3)
        
        window?.backgroundColor = UIColor.white
        window?.rootViewController = rootVc
        window?.makeKeyAndVisible()
        
        return true
    }
    
    
//    只有当应用程序位于前台时，才会在委托上调用该方法。如果方法没有实现，或者没有及时调用处理程序，则不会显示通知。应用程序可以选择将通知显示为声音、标识、警告和/或通知列表。这个决定应该基于通知中的信息是否对用户可见。
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {  // 远程推送
//            EaseSDKHelper.share()?.hyphenateApplication(UIApplication.shared, didReceiveRemoteNotification: notification.request.content.userInfo)
//            [[EMClient sharedClient] application:application didReceiveRemoteNotification:userInfo];
            EMClient.shared()?.application(UIApplication.shared, didReceiveRemoteNotification: notification.request.content.userInfo)
        } else {  //其它本地推送
            
        }
    }
//    当用户通过打开应用程序、取消通知或选择UNNotificationAction来响应通知时，将在委托上调用该方法。必须在应用程序从应用程序返回之前设置委托:didFinishLaunchingWithOptions:。
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
            print("进入聊天页面")
        } else {
            
        }
        completionHandler()
    }

    ////收到通知
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        
        EaseSDKHelper.share()?.hyphenateApplication(UIApplication.shared, didReceiveRemoteNotification: userInfo)
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        DispatchQueue.global().async {
            EMClient.shared()?.bindDeviceToken(deviceToken)
        }
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("注册deviceToken失败，此处失败，与环信SDK无关，一般是您的环境配置或者证书配置有误")
    }
    
    
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        EMClient.shared()?.applicationDidEnterBackground(application)
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        EMClient.shared()?.applicationWillEnterForeground(application)
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

